/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.sss.mapreduce.Configuration;
import org.sss.mapreduce.SssException;

/**
 * .
 * NOTE: This class is used by only this module.
 */
class SSSCLI {
  static String[] parse(String[] args, Configuration conf, Set<String> jars) throws SssException {
    Configuration confFromFile = new Configuration();
    Configuration confFromArgs = new Configuration();
    List<String> other = new ArrayList<String>();
    int i;
    for (i = 0;i < args.length;++i) {
      String arg = args[i];
      if (arg.equals("--") || !arg.startsWith("-")) {
        break;
      }

      if (arg.startsWith("--sss")) {
        // sss option
        String[] ov = arg.substring("--".length()).split("=", 2);
        String opt = ov[0];

        if (opt.equals("sss-conf")) {
          String optarg = getOptArg(ov);
          String[] kv = optarg.split("=", 2);

          confFromArgs.set(kv[0], (kv.length >= 2)?kv[1]:"");
        } else if (opt.equals("sss-conffile")) {
          confFromFile.load(getOptArg(ov));
        } else if (opt.equals("sss-jar")) {
          jars.add(getOptArg(ov));
        } else {
          throw new SssException("unkown command line option: " + opt);
        }
      } else {
        other.add(arg);
      }
    }

    for (;i < args.length;++i) {
      other.add(args[i]);
    }

    conf.merge(confFromFile);
    conf.merge(confFromArgs);

    return other.toArray(new String[other.size()]);
  }

  private static String getOptArg(String[] ov) throws SssException {
    if (ov.length < 2) {
      throw new SssException("required argument: " + ov[0]);
    }
    return ov[1];
  }
}
